package com.prj.ufdm.demo.tutorial.thread;

/**
 * 两个线程交替打印AA/BB
 * @author Administrator
 *
 */
public class TestWaitNotify2 {

	public static void main(String[] args) throws Exception {
		
		final TCThread tcThread = new TCThread();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i=0;i<10;i++) {
				    try {
						tcThread.printA();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i=0;i<10;i++) {
				    try {
						tcThread.printB();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();

	}
	
	
	static class TCThread {
		
		// A 是否获得锁
		boolean isAhasLock = true;
		
		synchronized void  printA() throws Exception {
			// 如果A获取锁，执行打印
			if(isAhasLock) {
				for(int i=0;i<2;i++) {
					System.out.println("AA");
				}
				isAhasLock = false;
				this.notify();
			}
			else {
				this.wait();
			}

		}
		
		synchronized void printB() throws Exception  {
			if(!isAhasLock) {
				for(int i=0;i<3;i++) {
					System.out.println("BB");
					isAhasLock = true;
				}
				this.notify();
			}
			else {
				this.wait();
			}
		}
	}
}
